#include "persistence.h"


list<string> Commando::result;
/**
pArg is a copy of the fourth argument to sqlite_exec(). This parameter is used to pass arbitrary information through to the callback function.
argc is the number of columns in the query result.
argv is an array of pointers to strings where each string is a single column of the result for that record.
colName is an array of pointers to the column names, possibly followed by column data types.
*/
int Commando::callback(void * num, int argc, char **argv, char **colName){
    int i;
    stringstream ss;



    (*(unsigned long *)num)++;

    if(*(unsigned long *)num==1){
        ss << endl << "\t";
        for(i=0; i<argc; i++){
          ss << colName[i] << " | ";
        }
    }
    ss << endl << *(unsigned long *)num << "\t  ";
    for(i=0; i<argc; i++){
      ss <<  argv[i] << " | ";
    }




    result.push_front(ss.str());

    return 0;
}

Persistence * Persistence::_instance = 0;

Persistence::Persistence(){
}

Persistence * Persistence::Instanciate(){
    if(_instance==0){
        _instance = new Persistence();
    }
    return _instance;
}

void Persistence::Conectar(){
    int rc;
    stringstream ss;

    rc = sqlite3_open("poo_albumphotos.db", &db);
    if(  rc!=SQLITE_OK  ){
        ss << endl << "banco de dados inacessivel: " << sqlite3_errmsg(db) << endl;
        throw(ss.str());
        sqlite3_close(db);
    }
}

void Persistence::Desconectar(){
    sqlite3_close(db);
}

int Persistence::callback(void *NotUsed, int argc, char **argv, char **azColName){
    int i;
    for(i=0; i<argc; i++){
      cout << endl << azColName[i] << " = " << argv[i] << endl;
    }
    return 0;
}

void Persistence::Executar(Commando * cmd){
    char *zErrMsg = 0;
    int rc;
    stringstream ss;
    const char * chp;
    try{
        Conectar();

        string str(cmd->query());
        chp = str.c_str();
        cmd->callback_count=0;

        rc = sqlite3_exec(db, chp, cmd->callback, &(cmd->callback_count), &zErrMsg);
        if( rc!=SQLITE_OK ){
            ss << endl << "problema ao executar query ("<< chp <<") no banco: " << zErrMsg << endl;
            sqlite3_free(zErrMsg);
            throw(ss.str());
        }

        Desconectar();
    }catch(string str){
        Desconectar();
        throw(str);
    }
}
